{% load static %}
<!DOCTYPE html>
<html lang="zh-CN">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>数据源管理系统</title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet" />
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap-icons@1.10.0/font/bootstrap-icons.css" />
    <style>
      .sidebar {
        height: 100vh;
        background-color: #343a40;
        color: white;
        padding-top: 20px;
      }
      .sidebar .nav-link {
        color: #adb5bd;
        border-radius: 0;
      }
      .sidebar .nav-link.active {
        background-color: #0d6efd;
        color: white;
      }
      .sidebar .nav-link:hover {
        color: white;
        background-color: #495057;
      }
      .content {
        padding: 20px;
      }
      .card-header {
        background-color: #f8f9fa;
        border-bottom: 1px solid rgba(0, 0, 0, 0.125);
      }
      .table-responsive {
        box-shadow: 0 0.125rem 0.25rem rgba(0, 0, 0, 0.075);
        border-radius: 0.25rem;
        overflow: hidden;
      }
      .btn-action {
        margin: 0 2px;
      }
      /* 表格整体样式 */
      .centered-table {
        margin: 0 auto; /* 表格居中显示在页面中 */
        border-collapse: collapse; /* 合并边框 */
      }

      /* 表头和内容单元格居中 */
      .centered-table th,
      .centered-table td {
        text-align: center; /* 文本水平居中 */
        vertical-align: middle; /* 文本垂直居中） */
        padding: 10px; /* 单元格内边距 */
        border: 1px solid #ddd; /* 边框样式 */
      }
    </style>
  </head>
  <body>
    <div class="container-fluid">
      <div class="row">
        <!-- 侧边栏 -->
        <div class="col-md-2 d-none d-md-block sidebar">
          <div class="text-center mb-4">
            <h3>数据管理</h3>
          </div>
          <ul class="nav flex-column">
            <li class="nav-item">
              <a class="nav-link active" href="{% url 'datasource_list' %}">
                <i class="bi bi-database me-2"></i>
                数据源管理
              </a>
            </li>
            <!-- <li class="nav-item">
              <a class="nav-link" href="{% url 'agent_management' %}">
                <i class="bi bi-robot me-2"></i>
                智能体管理
              </a>
            </li> -->
            <li class="nav-item">
              <a class="nav-link" href="{% url 'operation_log' %}">
                <i class="bi bi-clock-history me-2"></i>
                操作日志
              </a>
            </li>
          </ul>
        </div>

        <!-- 主内容区 -->
        <main class="col-md-10 ms-sm-auto px-md-4 content">
          <!-- 顶部导航 -->
          <nav class="navbar navbar-expand-lg navbar-light bg-light mb-4">
            <div class="container-fluid">
              <button class="navbar-toggler" type="button" data-bs-toggle="collapse" data-bs-target="#navbarNav">
                <span class="navbar-toggler-icon"></span>
              </button>
              <div class="collapse navbar-collapse" id="navbarNav">
                <ul class="navbar-nav me-auto">
                  <li class="nav-item">
                    <h4 class="nav-link">数据源管理</h4>
                  </li>
                </ul>
                <div class="d-flex">
                  <button class="btn btn-outline-secondary me-2">
                    <i class="bi bi-person me-1"></i>
                    登录
                  </button>
                </div>
              </div>
            </div>
          </nav>

          <!-- 数据源列表卡片 -->
          <div class="card mb-4">
            <div class="card-header d-flex justify-content-between align-items-center">
              <h5 class="mb-0">数据源列表</h5>
              <a href="{% url 'datasource_create' %}" class="btn btn-primary">
                <i class="bi bi-plus-circle me-1"></i>
                新建数据源
              </a>
            </div>
            <div class="card-body">
              <!-- 搜索框 -->
              <div class="input-group mb-3">
                <input type="text" class="form-control" id="searchInput" placeholder="搜索数据源名称..." />
                <button class="btn btn-outline-secondary" type="button" id="searchBtn">
                  <i class="bi bi-search"></i>
                  搜索
                </button>
                <button class="btn btn-outline-primary" type="button" id="resetBtn">
                  <i class="bi bi-arrow-clockwise"></i>
                  重置
                </button>
              </div>

              <!-- 数据源表格 -->
              <div class="table-responsive">
                <table class="table table-striped table-hover centered-table">
                  <thead class="table-light">
                    <tr>
                      <th>名称</th>
                      <th>表格数量</th>
                      <th>创建时间</th>
                      <th>连接状态</th>
                      <th>操作</th>
                    </tr>
                  </thead>
                  <tbody>
                    {% for datasource in datasources %}
                    <tr>
                      <td>{{ datasource.name }}</td>
                      <td>{{ datasource.table_count }}</td>
                      <td>{{ datasource.created_at|date:'Y-m-d H:i:s' }}</td>
                      <td>
                        {% if datasource.connection_status %}
                        <span class="text-success">已连接</span>
                        {% else %}
                        <span class="text-danger">未连接</span>
                        {% endif %}
                      </td>
                      <td>
                        <div class="btn-group btn-group-sm">
                          <a href="{% url 'datasource_config' datasource.id %}" class="btn btn-outline-primary btn-action">配置</a>
                          <a href="{% url 'datasource_edit' datasource.id %}" class="btn btn-outline-secondary btn-action">编辑</a>
                          <button class="btn btn-outline-danger btn-action" data-bs-toggle="modal" data-bs-target="#deleteModal{{ datasource.id }}">删除</button>
                        </div>

                        <!-- 删除确认模态框 -->
                        <div class="modal fade" id="deleteModal{{ datasource.id }}" tabindex="-1">
                          <div class="modal-dialog">
                            <div class="modal-content">
                              <div class="modal-header">
                                <h5 class="modal-title">确认删除</h5>
                                <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
                              </div>
                              <div class="modal-body">
                                <p>
                                  确定要删除数据源
                                  <strong>{{ datasource.name }}</strong>
                                  吗？此操作不可恢复。
                                </p>
                              </div>
                              <div class="modal-footer">
                                <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">取消</button>
                                <form action="{% url 'datasource_delete' datasource.id %}" method="post">
                                  {% csrf_token %}
                                  <button type="submit" class="btn btn-danger">删除</button>
                                </form>
                              </div>
                            </div>
                          </div>
                        </div>
                      </td>
                    </tr>
                    {% empty %}
                    <tr>
                      <td colspan="5" class="text-center">暂无数据源，请点击上方"新建数据源"按钮创建</td>
                    </tr>
                    {% endfor %}
                  </tbody>
                </table>
              </div>
            </div>
          </div>

          <!-- 页脚 -->
          <footer class="text-center text-muted">
            <p>&copy; 2025 数据源管理系统 | 使用 Django 构建</p>
          </footer>
        </main>
      </div>
    </div>

    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/js/bootstrap.bundle.min.js"></script>
    <script>
      // 获取按钮和输入框元素
      const searchBtn = document.getElementById('searchBtn')
      const resetBtn = document.getElementById('resetBtn')
      const searchInput = document.getElementById('searchInput')
      const tableRows = document.querySelectorAll('tbody tr')

      // 搜索功能
      function performSearch() {
        const keyword = searchInput.value.trim().toLowerCase()
        let hasResults = false

        tableRows.forEach((row) => {
          // 跳过"暂无数据"的行
          if (row.cells.length === 1) return

          const nameCell = row.cells[0] // 名称列
          const nameText = nameCell.textContent.toLowerCase()

          if (keyword === '' || nameText.includes(keyword)) {
            row.style.display = ''
            hasResults = true
          } else {
            row.style.display = 'none'
          }
        })

        // 显示或隐藏"暂无搜索结果"提示
        const noResultsRow = document.querySelector('.no-results-row')
        if (keyword && !hasResults) {
          if (!noResultsRow) {
            const tbody = document.querySelector('tbody')
            const noResults = document.createElement('tr')
            noResults.className = 'no-results-row'
            noResults.innerHTML = '<td colspan="5" class="text-center">没有找到匹配的数据源</td>'
            tbody.appendChild(noResults)
          }
        } else {
          if (noResultsRow) {
            noResultsRow.remove()
          }
        }
      }

      // 重置功能
      function resetSearch() {
        searchInput.value = ''
        tableRows.forEach((row) => {
          row.style.display = ''
        })

        // 移除"暂无搜索结果"提示
        const noResultsRow = document.querySelector('.no-results-row')
        if (noResultsRow) {
          noResultsRow.remove()
        }

        // 恢复原始的"暂无数据源"提示（如果需要）
        const emptyRow = document.querySelector('.empty-row')
        const tbody = document.querySelector('tbody')
        if (tbody.children.length === 0) {
          const emptyTr = document.createElement('tr')
          emptyTr.className = 'empty-row'
          emptyTr.innerHTML = '<td colspan="5" class="text-center">暂无数据源，请点击上方"新建数据源"按钮创建</td>'
          tbody.appendChild(emptyTr)
        }
      }

      // 绑定事件
      searchBtn.addEventListener('click', performSearch)
      resetBtn.addEventListener('click', resetSearch)

      // 实时搜索（输入时触发，带防抖）
      // let searchTimeout
      // searchInput.addEventListener('input', function() {
      //   clearTimeout(searchTimeout)
      //   searchTimeout = setTimeout(performSearch, 300)
      // })

      // 回车键搜索
      // searchInput.addEventListener('keypress', function(e) {
      //   if (e.key === 'Enter') {
      //     performSearch()
      //   }
      // })

      // 初始化：从URL参数中获取搜索关键词
      const urlParams = new URLSearchParams(window.location.search)
      const searchTerm = urlParams.get('search')
      if (searchTerm) {
        searchInput.value = searchTerm
        performSearch()
      }
    </script>
  </body>
</html>
